import styles from './pwd.module.less'
import Modal from '@/components/modal'
import Button from '@/components/button'
import cm from 'classnames'
import Input from '@/components/input'
import { useCountDown, useSetState } from 'ahooks'
import { useRef, useState, useEffect } from 'react'
import { validPwd, surePwd, handleLocalUserInfo } from '@/utils/utils'
import { getCode, updatePwd } from '@/api/user'
import { useUserInfo } from '@/utils/hooks'
import { debounce } from 'lodash-es'
import { cncryptionCipher } from '@/utils/encode'
import Toast from '@/components/toast'

const Index = (props) => {
  const submitRef = useRef()
  const { visible, close } = props
  const { clearUserToken } = handleLocalUserInfo()
  const [formInfo, setFormInfo] = useSetState({})
  const { user } = useUserInfo()
  const [targetDate, setTargetDate] = useState(0)

  const [countdown] = useCountDown({
    targetDate,
  })

  //获取验证码
  const fetchCode = async () => {
    setTargetDate(Date.now() + 60000)
    const res = await getCode({ email: user.email })
    if (!res.code) {
      Toast.normal('已发送验证码至邮箱，请查收')
    }
  }
  const debounceFetchCode = debounce(fetchCode, 100)
  const GetCodeDom = (
    <div className={styles.getCode}>
      {countdown ? (
        <span className={styles.wait}>{Math.round(countdown / 1000)}s后重发</span>
      ) : (
        <span className={styles.code} onClick={debounceFetchCode}>
          获取验证码
        </span>
      )}
    </div>
  )

  const onSubmit = async () => {
    const isValidPwd = validPwd(formInfo.password)
    const isSurePwd = surePwd(formInfo.repwd)
    setFormInfo({
      pwdErr: !isValidPwd,
      repwdErr: !formInfo.repwd,
      codeErr: !formInfo.code,
    })
    if (!isValidPwd || !isSurePwd || !formInfo.code) {
      return
    }
    const res = await updatePwd({
      password: cncryptionCipher(formInfo.password),
      code: formInfo.code,
      email: user.email,
    })
    if (!res.code) {
      clearUserToken()
      Toast.normal('密码修改成功，请重新登录')
      setTimeout(() => {
        window.location.replace('/login')
      }, 1500)
    }
  }

  useEffect(() => {
    const down = (e) => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    window.addEventListener('keydown', down)
    return () => {
      window.removeEventListener('keydown', down)
    }
  }, [])

  return (
    <Modal visible={visible}>
      <div className={styles.pwd}>
        <h1 className={styles.title}>修改密码</h1>
        <img src="/images/close.webp" className={styles.close} onClick={close} />
        <p className={styles.inputLabel}>
          <span>新密码</span>
          {formInfo.pwdErr && <span>密码不符合要求请重新输入</span>}
        </p>
        <p className={cm(styles.inputLabel, styles.inputTip)}>须是6-20个英文字母、数字，且以上两种必须都包含</p>
        <Input
          id="pwd"
          inputClass="input"
          placeholder="请输入您的密码"
          onChange={(e) => setFormInfo({ password: e.target.value })}
          hasSuffix
        />
        <p className={styles.inputLabel}>
          <span>确认密码</span>
          {formInfo.repwdErr && <span>两次密码不一致，请确认</span>}
        </p>
        <Input
          inputClass="input"
          id="pwdSecond"
          placeholder="请再次输入您的密码"
          onChange={(e) => setFormInfo({ repwd: e.target.value })}
          hasSuffix
        />
        <p className={styles.inputLabel}>
          <span>验证码</span>
          {formInfo.codeErr && <span>验证码无效请重新输入</span>}
        </p>
        <Input placeholder="请输入验证码" onChange={(e) => setFormInfo({ code: e.target.value })} suffix={GetCodeDom} />
        <Button onClick={onSubmit} ref={submitRef} className={styles.submit}>
          确认提交
        </Button>
      </div>
    </Modal>
  )
}

export default Index
